import React from 'react';
import ReactDOM from 'react-dom';
import { Spin, Popconfirm, message } from 'antd';
import { WeaErrorPage, WeaTools } from 'ecCom';
const { ls } = WeaTools;
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import ESetting from '../common/setting_new/ESetting';
import { isContain, onSetting, openMoreWin, hpinfoHandle, isNoMoreElement } from '../../util/common';
class OpToolbar extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                islock: '',
                icon: '',
                moreRouteurl: ''
            }
            this.handleLock = this.handleLock.bind(this);
            this.handleOnSetting = this.handleOnSetting.bind(this);
            this.handleDelete = this.handleDelete.bind(this);
            this.onMoreClick = this.onMoreClick.bind(this);
        }

        componentDidMount(){
            //判断流程元素是否存在自定义more页面
            const { config } = this.props;
            const { eid, ebaseid } = config.params;
            let moreRouteurl = '';
            if(ebaseid == '8' || ebaseid == '7') {
                WeaTools.callApi('/api/portal/customMore/getRouteurl', 'POST', {ebaseid, eid}).then(result => {
                    if(result.status == '200' && result.moreRouteurl){
                        this.setState({
                            moreRouteurl: result.moreRouteurl
                        })
                    }
                });
            }
        }

        handleDelete(){
            const { config, handleDelete } = this.props;
            const { eid, hpid, subCompanyId } = config.params;
            var group = $($("#item_"+eid).parents(".group")[0]);
            var flag = group.attr('data-areaflag');
            var eids = "";
            group.find(".item").each(function(){
               if($(this).attr("data-eid") != eid && $(this).attr("data-eid") != undefined) {
                   eids += $(this).attr("data-eid")+",";
               }
            });
            let portalHpinfo_setting = ls.getJSONObj('portal-'+ hpid + '-true');
            let portalHpinfo = ls.getJSONObj('portal-'+ hpid + '-false');
            portalHpinfo_setting && ls.set('portal-'+ hpid + '-true', hpinfoHandle(portalHpinfo_setting, eid));
            portalHpinfo && ls.set('portal-'+ hpid + '-false', hpinfoHandle(portalHpinfo, eid));
            WeaTools.callApi('/api/portal/elementtoolbar/delete', 'POST', {
                hpid,
                eid,
                delFlag: flag,
                delAreaElement: eids,
                subCompanyId,
            }).then(result=> {
                if(result.status == "sucess")  {
                    handleDelete();
                } else {
                    message.error(getLabel(83912, '操作失败！'), 3);
                }
            });
        }
        handleLock(){
            const { islock } = this.state;
            const { eid, hpid, subCompanyId } = this.props.config.params;
            WeaTools.callApi('/api/portal/elementtoolbar/'+ (islock ? 'unlock' : 'lock'), 'POST', {
               eid,
               hpid,
               subCompanyId,
            }).then(result=> {
                if(result.status == "sucess")  {
                    this.setState({
                        islock: !islock,
                        icon: result.icon
                    });
                } else {
                    message.error(getLabel(83912, '操作失败！'), 3);
                }
            });
        }
        handleOnSetting() {
            const { config, handleRefresh } = this.props;
            const { isSynergySetting, synergyParams } =  config;
            const { eid, ebaseid, hpid, subCompanyId } = config.params;
            const readyElement = [
                '1', '7', '8', '11', '12', '6', '13', '14', '15', '16', '9', '10', '17', '18', '19', '25', '29', '32', '34',
                'audio', 'blogStatus', 'favourite', 'Flash', 'menu', 'notice', 'picture', 'reportForm', 'searchengine', 'Slide',
                'video', 'weather', 'scratchpad', 'DataCenter', 'MyCalendar', 'Task', 'plan', 'jobsinfo', 'outterSys', 'contacts',
                'addwf', 'imgSlide', 'newNotice', 'OutData','FormModeCustomSearch','MeetingCalendar', 'CalendarEle', 'bookshelf',
                'newMobilePicture', 'fnaBudgetAssistant', 'fnaBudgetAssistant1', 'CoreMail', 'news', 'processTask', 'login','NEW_DY',
                'quickEntry', 'ecodeElement','odocCenter','RankingList'
            ];
            if (isContain(readyElement, ebaseid) || /^Custom_/.test(ebaseid)) {
                ReactDOM.render(<div style={{textAlign: 'center'}}><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@gbeasq`} /></div>,  $(`.homepage[data-isSetting=${config.isSetting}] #setting_${eid}`)[0]);
                WeaTools.callApi('/api/portal/setting/esetting', 'POST', {eid, ebaseid, hpid, subCompanyId}, 'json').then(function (result) {
                    result.hpid = hpid;
                    result.subCompanyId = subCompanyId;
                    result.eid = eid;
                    result.ebaseid = ebaseid;
                    ReactDOM.render(<ESetting ecId={`${this && this.props && this.props.ecId || ''}_ESetting@ux9smb`} data={result} isSynergySetting={isSynergySetting} synergyParams={synergyParams} handleRefresh={handleRefresh} isSetting={config.isSetting}/>,  $(`.homepage[data-isSetting=${config.isSetting}] #setting_${eid}`)[0]);
                });
            } else {
                onSetting(eid, ebaseid, hpid, subCompanyId);
            }
        }

        onMoreClick = (eid, ebaseid, _moreurl, moreRouteurl) => {
            const { customClickMore} = this.props;
            if(typeof customClickMore === "function")
                customClickMore(eid, ebaseid, _moreurl, moreRouteurl);
            else
                openMoreWin(eid, ebaseid, _moreurl, moreRouteurl);
        }

        render() {
           const { config, clsname, islock, handleRefresh, needMore = true  } = this.props;
           const { eid, ebaseid, header } = config.item;
           const { toolbar } = header;
           const { lock, refresh, setting, close, more } = toolbar;
           const { icon, moreRouteurl } = this.state;
           return <div className={'optoolbar ' + clsname} id={`toolbar_${eid}`}>
                  <ul>
                    {lock ? <li style={{width:'11px'}}>
                      <Popconfirm ecId={`${this && this.props && this.props.ecId || ''}_Popconfirm@l9vek6`} title={getLabel(19745, '此操作可能花较长的时间，是否继续？')} onConfirm={this.handleLock} cancelText={getLabel(31129, '取消')} okText={getLabel(826, '确定')}>
                        <a data-status={islock?'locked':'unlocked'} href="javascript:void(0);" title={lock.title}>
                        <img src={icon || lock.img} border="0" alt=''/></a>
                        </Popconfirm>
                    </li> : ''}
                    {refresh ? <li style={{width:'11px'}}>
                      <a href="javascript:void(0);" name="refreshbtn" id={`refresh_${eid}`} onClick={handleRefresh} title={refresh.title}>
                        <img src={refresh.img} border="0" alt=''/></a>
                      </li> : ''}
                    {setting ? <li style={{width:'12px'}}>
                      <a href="javascript:void(0)" onClick={this.handleOnSetting} title={setting.title}>
                        <img className="img_setting" src={setting.img} border="0" alt=''/></a>
                    </li> : ''}
                    {close ? <li style={{width:'12px'}}>
                        <Popconfirm ecId={`${this && this.props && this.props.ecId || ''}_Popconfirm@7ykx06`} placement="leftTop"  title={getLabel(19747, '此元素被删除后将不能被恢复，是否继续？')} onConfirm={this.handleDelete} cancelText={getLabel(31129, '取消')} okText={getLabel(826, '确定')}>
                          <a href="javascript:void(0);" title={close.title}>
                            <img src={close.img} border="0" alt=''/></a>
                        </Popconfirm>
                    </li> : ''}
                      {more && more.position=='title' && needMore ? (
                          isNoMoreElement(ebaseid) && !moreRouteurl ? '':
                          <li style={{width:'34px'}}>
                              <a id={`more_${eid}`} href="javascript:void(0);" onClick={() =>this.onMoreClick(eid, ebaseid, more.morehref, moreRouteurl)}>
                                  <img className="img_more" id="imgMore" border="0" src={more.img} title={more.title} alt=''/></a>
                          </li>
                      ) : ''}
                </ul>
              </div>
    }
}


class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
           return (<WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@v5yjne`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！")} />
        );
    }
}
OpToolbar = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(OpToolbar);
export default OpToolbar;



